package Service;

/**
 * @Author Su
 * @Date 2025/5/1 16:15
 * @Version 1.0 （版本号）
 */
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class CaptchaStoreService {
    private static final Map<String, String> captchaStore = new ConcurrentHashMap<>();
    //todo：定义一个常量类保存
    private static final long CAPTCHA_EXPIRE_MINUTES = 1;

    // 存储验证码
    public static void storeCaptcha(String sessionId, String captchaText) {
        captchaStore.put(sessionId, captchaText);

        // 定时移除过期验证码
        new Thread(() -> {
            try {
                TimeUnit.MINUTES.sleep(CAPTCHA_EXPIRE_MINUTES);
                captchaStore.remove(sessionId);
            } catch (InterruptedException ignored) {}
        }).start();
        System.out.println("当前验证码列表：" + captchaStore);
    }

    // 验证验证码
    public static boolean validateCaptcha(String sessionId, String inputCaptcha) {
        System.out.println("进入验证验证码");
        if (inputCaptcha == null || inputCaptcha.isEmpty()) {
            return false;
        }

        String storedCaptcha = captchaStore.get(sessionId);
        System.out.println("sessionId" + sessionId);
        if (storedCaptcha == null) {
            return false;
        }

        captchaStore.remove(sessionId); // 验证后移除
        return storedCaptcha.equalsIgnoreCase(inputCaptcha);
    }
}